use std::thread;
use std::time::Duration;
use std::sync::mpsc;

fn main() {
    
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
        // println!("val is {val}"); // tx.send 函数 拥有其参数的所有权，当值被移动时，接收者 拥有它。这防止我们在发送值后意外再次使用该值；
    });

    // try_recv 不会阻塞，而是会立即返回一个Result<T, E>
    // recv 阻止主线程的执行并等待 直到一个值通过通道发送下来
    let received = rx.recv().unwrap();
    println!("Got: {received}");
    
    let (tx, rx) = mpsc::channel();
    let tx1 = tx.clone();
    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];

        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

    thread::spawn(move || {
        let vals = vec![
            String::from("more"),
            String::from("messages"),
            String::from("for"),
            String::from("you"),
        ];

        for val in vals {
            tx1.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

    for received in rx {
        println!("Got: {received}");
    }
}
